package com.net.oil.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import
androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.net.oil.R;
import com.net.oil.app.Constant;
import com.net.oil.base.BaseActivity;
import com.net.oil.gaode.RoutePlanActivity;
import com.net.oil.http.AppUrl;
import com.net.oil.order.adapter.MaintainUseSubsidiaryRecyclerViewAdapter;
import com.net.oil.order.bean.MaintainDetailBean;
import com.net.oil.order.contract.MaintainDetailContract;
import com.net.oil.order.presenter.MaintainDetailPresenter;
import com.net.oil.product.ProductDetailActivity;
import com.net.oil.util.DateFormat;
import com.net.oil.util.glide.GlideUtil;
import com.net.oil.widget.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MaintainDetailActivity extends BaseActivity<MaintainDetailPresenter> implements MaintainDetailContract.View {

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.reserve_time_tv)
    TextView reserveTimeTv;
    @BindView(R.id.shop_logo)
    ImageView shopLogo;
    @BindView(R.id.take_me_to_layout)
    LinearLayout takeMeToLayout;
    @BindView(R.id.shop_name)
    TextView shopName;
    @BindView(R.id.shop_address)
    TextView shopAddress;
    @BindView(R.id.right_icon)
    ImageView rightIcon;
    @BindView(R.id.shop_phone)
    TextView shopPhone;
    @BindView(R.id.shop_phone_layout)
    RelativeLayout shopPhoneLayout;
    @BindView(R.id.maintain_oil_img)
    ImageView maintainOilImg;
    @BindView(R.id.maintain_oil_name_tv)
    TextView maintainOilNameTv;
    @BindView(R.id.maintain_oil_layout)
    LinearLayout maintainOilLayout;
    @BindView(R.id.brake_oil_img)
    ImageView brakeOilImg;
    @BindView(R.id.brake_oil_name_tv)
    TextView brakeOilNameTv;
    @BindView(R.id.brake_oil_layout)
    LinearLayout brakeOilLayout;
    @BindView(R.id.gearbox_oil_img)
    ImageView gearboxOilImg;
    @BindView(R.id.gearbox_oil_name_tv)
    TextView gearboxOilNameTv;
    @BindView(R.id.gearbox_oil_layout)
    LinearLayout gearboxOilLayout;
    @BindView(R.id.available_mileage_tv)
    TextView availableMileageTv;
    @BindView(R.id.mileage_tv)
    TextView mileageTv;
    @BindView(R.id.subsidiary_product_recycler_view)
    RecyclerView subsidiaryProductRecyclerView;
    @BindView(R.id.coupon_tv)
    TextView couponTv;
    @BindView(R.id.rating_bar)
    RatingBar ratingBar;
    @BindView(R.id.commit_but)
    Button commitBut;
    @BindView(R.id.comment_et)
    EditText commentEt;

    private int recordId = -1;
    private MaintainDetailBean maintainDetailBean;

    private MaintainUseSubsidiaryRecyclerViewAdapter maintainUseSubsidiaryRecyclerViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintain_detail);
        ButterKnife.bind(this);
        presenter = new MaintainDetailPresenter(this);
        initData();
        initView();

    }

    private void initData() {
        recordId = getIntent().getIntExtra(Constant.INTENT_RECORD_ID, -1);
        if (recordId != -1) {
            showProgressDialog();
            presenter.getMaintainDetail(recordId);
        }
    }

    private void initView() {
        toolbarTitle.setText("保养记录详情");
        maintainUseSubsidiaryRecyclerViewAdapter = new MaintainUseSubsidiaryRecyclerViewAdapter(this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        subsidiaryProductRecyclerView.setLayoutManager(manager);
        subsidiaryProductRecyclerView.setAdapter(maintainUseSubsidiaryRecyclerViewAdapter);

        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {

            }
        });

        /* 修复星星流泪 */
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.stars_bright);
        int starsImgHeight = bmp.getHeight();
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) ratingBar.getLayoutParams();
        lp.width = LinearLayout.LayoutParams.WRAP_CONTENT;
        lp.height = starsImgHeight;
        ratingBar.setLayoutParams(lp);
    }

    /**
     * 获取保养记录详情成功
     *
     * @param maintainDetailBean 记录详情
     */
    @Override
    public void getMaintainDetailSuccess(final MaintainDetailBean maintainDetailBean) {
        dismissProgressDialog();
        if (maintainDetailBean != null) {
            this.maintainDetailBean = maintainDetailBean;
            reserveTimeTv.setText(DateFormat.formatDateTime(maintainDetailBean.getT(), DateFormat.FormatFlag.YDMHM));

            /* 机油信息，如果id不为空，则点击跳转到产品详情 */
            if (maintainDetailBean.getOilProductId() != null) {
                maintainOilLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MaintainDetailActivity.this, ProductDetailActivity.class);
                        intent.putExtra(Constant.INTENT_PRODUCT_DETAIL_ID, maintainDetailBean.getOilProductId());
                        startActivity(intent);
                    }
                });
            }
            if (!TextUtils.isEmpty(maintainDetailBean.getOilProductName())) {
                maintainOilNameTv.setText(maintainDetailBean.getOilProductName());
            }
            GlideUtil.getInstance().loadImage(this, maintainOilImg,
                    AppUrl.getImageUrl(maintainDetailBean.getOilProductImage()), R.drawable.product_err);

            /* 刹车油信息，如果id不为空，则跳转到产品详情 */
            if (maintainDetailBean.getBrakeProductId() != null) {
                brakeOilLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MaintainDetailActivity.this, ProductDetailActivity.class);
                        intent.putExtra(Constant.INTENT_PRODUCT_DETAIL_ID, maintainDetailBean.getBrakeProductId());
                        startActivity(intent);
                    }
                });
            }
            if (!TextUtils.isEmpty(maintainDetailBean.getBrakeProductName())) {
                brakeOilNameTv.setText(maintainDetailBean.getBrakeProductName());
            }
            GlideUtil.getInstance().loadImage(this, brakeOilImg,
                    AppUrl.getImageUrl(maintainDetailBean.getBrakeProductImage()), R.drawable.product_err);

            /* 变速箱油，如果id不为空，则跳转到产品详情 */
            if (maintainDetailBean.getGearboxProductId() != null) {
                gearboxOilLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MaintainDetailActivity.this, ProductDetailActivity.class);
                        intent.putExtra(Constant.INTENT_PRODUCT_DETAIL_ID, maintainDetailBean.getGearboxProductId());
                        startActivity(intent);
                    }
                });
            }
            if (!TextUtils.isEmpty(maintainDetailBean.getGearboxProductName())) {
                gearboxOilNameTv.setText(maintainDetailBean.getGearboxProductName());
            }
            GlideUtil.getInstance().loadImage(this, gearboxOilImg,
                    AppUrl.getImageUrl(maintainDetailBean.getGearboxProductImage()), R.drawable.product_err);

            /* 门店信息 */
            if (maintainDetailBean.getBusiness() != null) {
                MaintainDetailBean.BusinessBean business = maintainDetailBean.getBusiness();
                if (!TextUtils.isEmpty(business.getName())) {
                    shopName.setText(business.getName());
                }
                if (!TextUtils.isEmpty(business.getImagesStr())) {
                    GlideUtil.getInstance().loadImage(this, shopLogo, AppUrl.getImageUrl(business.getImagesStr()), R.drawable.shop_err);
                }
                if (!TextUtils.isEmpty(business.getPhone())) {
                    shopPhone.setText(business.getPhone());
                }
            }

            /* 配件 */
            if (maintainDetailBean.getUseSubsidiaryProductItemList() != null) {
                maintainUseSubsidiaryRecyclerViewAdapter.updateDatas(maintainDetailBean.getUseSubsidiaryProductItemList());
            }

            /* 保养里程周期 */
            availableMileageTv.setText(String.format(getString(R.string.available_mileage_format), maintainDetailBean.getAvailableMileage()));

            /* 保养时行驶公里数 */
            mileageTv.setText(String.format(getString(R.string.mileage_format), maintainDetailBean.getMileage()));

            /* 使用优惠券信息 */
            MaintainDetailBean.OilAppliment oilAppliment = maintainDetailBean.getOilAppliment();
            if (oilAppliment != null) {
                double amount = oilAppliment.getAmount();
                couponTv.setText(String.valueOf(amount));
            }

            /* 评论 */
            MaintainDetailBean.OilBusinessMaintainUserComment userComment = maintainDetailBean.getOilBusinessMaintainUserComment();
            if (userComment != null && maintainDetailBean.getCommentStatus() == 1) {
                //commentStatus（1：已经评论过 0：待评论）
                ratingBar.setRating(userComment.getScore());
                ratingBar.setIsIndicator(true);
                commitBut.setVisibility(View.INVISIBLE);
                if (userComment.getCommentDesc() != null){
                    commentEt.setText(userComment.getCommentDesc());
                    commentEt.setEnabled(false);
                }
            }
        }
    }

    /**
     * 获取记录详情失败
     */
    @Override
    public void getMaintainDetailFailed() {
        dismissProgressDialog();
    }

    @Override
    public void commitCommentSuccess() {
        dismissProgressDialog();
        ToastUtil.showSuccessToast(this, "评论成功");
        commentEt.setEnabled(false);
        ratingBar.setIsIndicator(true);
        commitBut.setVisibility(View.INVISIBLE);
    }

    @Override
    public void commitCommentFailed() {
        dismissProgressDialog();
        ToastUtil.showErrorToast(this, "评论失败");
    }

    @OnClick({R.id.toolbar_go_back, R.id.take_me_to_layout, R.id.shop_phone_layout, R.id.maintain_oil_img,
            R.id.brake_oil_img, R.id.gearbox_oil_img, R.id.commit_but})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_go_back:
                finish();
                break;
            case R.id.take_me_to_layout:
                Intent intent = new Intent(this, RoutePlanActivity.class);

                if (maintainDetailBean != null) {
                    MaintainDetailBean.BusinessBean businessBean = maintainDetailBean.getBusiness();
                    if (businessBean != null) {
                        intent.putExtra(Constant.INTENT_LNG, businessBean.getLng());
                        intent.putExtra(Constant.INTENT_LAT, businessBean.getLat());
                    }
                }
                startActivity(intent);
                break;
            case R.id.shop_phone_layout:
                if (maintainDetailBean != null) {
                    MaintainDetailBean.BusinessBean businessBean = maintainDetailBean.getBusiness();
                    if (businessBean != null) {
                        if (!TextUtils.isEmpty(businessBean.getPhone())) {
                            showCallDialog(businessBean.getPhone());
                        }
                    }
                }
                break;
            case R.id.maintain_oil_img:
                Intent intent1 = new Intent(this, ProductDetailActivity.class);
                if (maintainDetailBean.getOilProductId() != null) {
                    intent1.putExtra(Constant.INTENT_PRODUCT_DETAIL_ID, maintainDetailBean.getOilProductId());
                    startActivity(intent1);
                }
                break;
            case R.id.brake_oil_img:
                if (maintainDetailBean.getBrakeProductId() != null) {
                    Intent intent2 = new Intent(this, ProductDetailActivity.class);
                    intent2.putExtra(Constant.INTENT_PRODUCT_DETAIL_ID, maintainDetailBean.getBrakeProductId());
                    startActivity(intent2);
                }
                break;
            case R.id.gearbox_oil_img:
                if (maintainDetailBean.getGearboxProductId() != null) {
                    Intent intent3 = new Intent(this, ProductDetailActivity.class);
                    intent3.putExtra(Constant.INTENT_PRODUCT_DETAIL_ID, maintainDetailBean.getGearboxProductId());
                    startActivity(intent3);
                }
                break;
            case R.id.commit_but:
                commitComment();
                break;
            default:
                break;
        }
    }

    private void commitComment() {
        int score = (int) ratingBar.getRating();
        int id = maintainDetailBean.getId();
        String commentDesc = commentEt.getText().toString();
        presenter.commitComment(id, score, commentDesc);
        showProgressDialog();
    }

    /**
     * 拨打电话
     *
     * @param phoneNumber 电话号码
     */
    private void showCallDialog(final String phoneNumber) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("联系商家");
        builder.setMessage(phoneNumber);
        builder.setPositiveButton("联系商家", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Uri uri = Uri.parse("tel:" + phoneNumber);
                Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

}
